package com.financial.sys.service.register.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.financial.model.pojo.TLoginLog;
import com.financial.model.pojo.TUserAccount;
import com.financial.model.pojo.TUserInfo;
import com.financial.model.pojo.TUserWallet;
import com.financial.sys.mapper.register.LoginLogMapper;
import com.financial.sys.mapper.register.LoginMapper;
import com.financial.sys.mapper.user.TUserInfosMapper;
import com.financial.sys.mapper.user.TUserWalletsMapper;
import com.financial.sys.service.register.registerAndLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

@Service
public class RegisterAndLoginServiceImpl extends ServiceImpl<LoginMapper, TUserAccount> implements registerAndLoginService {

    @Autowired
    private LoginLogMapper loginLogMapper;

    @Autowired
    private TUserWalletsMapper tUserWalletMapper;

    @Autowired
    private TUserInfosMapper tUserInfoMapper;

    @Override
    public TUserAccount findUsernameAndPassword(String username,String password) {
        QueryWrapper<TUserAccount> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username).eq("password",password);
        TUserAccount userAccount=baseMapper.selectOne(queryWrapper);

        //获取日期
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());

        if(userAccount!=null){
            //更新数据库用户最后一次登录时间
            userAccount.setId(userAccount.getId());
            userAccount.setLastLoginTime(date);
            baseMapper.updateById(userAccount);

            //将该登录用户存到日志中
            TLoginLog tLoginLog=new TLoginLog();
            tLoginLog.setUsername(username);
            //获取电脑id
            tLoginLog.setIp(getHostIp());
            tLoginLog.setLoginResult(1); //登录结果(1:成功，0:失败)
            tLoginLog.setCreateTime(userAccount.getCreateTime());
            tLoginLog.setLoginTime(date);
            tLoginLog.setAccountType(userAccount.getAccountType());
            loginLogMapper.insert(tLoginLog);
            return userAccount;
        }
        //查询该密码错误登录失败用户，但是数据库存在该用户获取该用户的相关信息存到登录日志表
        QueryWrapper<TUserAccount> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("username",username);
        TUserAccount userAccount1=baseMapper.selectOne(queryWrapper1);
        //将该登录用户存到日志中
        TLoginLog tLoginLog=new TLoginLog();
        tLoginLog.setUsername(username);
        tLoginLog.setIp(getHostIp());
        tLoginLog.setLoginTime(date);
        tLoginLog.setLoginResult(0);//登录结果(1:成功，0:失败)
        tLoginLog.setAccountType(1);
        tLoginLog.setCreateTime(userAccount1.getCreateTime());
        loginLogMapper.insert(tLoginLog);
        return null;
    }

    @Override
    public int UserAdd(String username, String password) {
        TUserAccount userAccount=new TUserAccount();
        userAccount.setId(userAccount.getId());
        userAccount.setUsername(username);
        userAccount.setPassword(password);
        //新注册的用户状态默认为1 状态( 0:禁用, 1:正常 )
        userAccount.setAccountStatus(1);
        //新注册的用户状态默认为1 账户类型( 1:普通用户, 2:运营人员 )
        userAccount.setAccountType(1);
        //新注册用户信息默认为0 是否完善个人信息( 0:未完善, 1:已完善 )
        userAccount.setFillUserinfo(0);
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        userAccount.setCreateTime(date);

        int i=baseMapper.insert(userAccount);


        //用户详情信息添加该用户
        TUserInfo tUserInfo=new TUserInfo();
        tUserInfo.setAccountId(userAccount.getId());
        tUserInfo.setCreateTime(date);
        tUserInfoMapper.insert(tUserInfo);
        if(tUserInfo.getRealname()==null){
            //用户钱包信用分100
            TUserWallet tUserWallet=new TUserWallet();
            //获取用户id
            tUserWallet.setAccountId(userAccount.getId());
            tUserWallet.setCreditScore(100);
            tUserWallet.setAvailableAmount(1000000L);
            tUserWallet.setCreditLine(1000000L);
            tUserWallet.setResidualCreditLine(1000000L);
            tUserWallet.setCreateTime(date);
            tUserWalletMapper.insert(tUserWallet);
        }

        return i;
    }

    @Override
    public boolean checkUsername(String username) {
        //查询用户是否存在
        QueryWrapper<TUserAccount>queryWrapper=new QueryWrapper();
        queryWrapper.eq("username",username);
        TUserAccount userAccount=(TUserAccount)baseMapper.selectOne(queryWrapper);
        if(userAccount!=null){
            return false;
        }
        return true;
    }

    //获得本机ip
    private static String getHostIp(){
        try{
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()){
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()){
                    InetAddress ip = (InetAddress) addresses.nextElement();
                    if (ip != null
                            && ip instanceof Inet4Address
                            && !ip.isLoopbackAddress() //loopback地址即本机地址，IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
                            && ip.getHostAddress().indexOf(":")==-1){
                        System.out.println("本机的IP = " + ip.getHostAddress());
                        return ip.getHostAddress();
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
